import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
	  state: {
		    isLogin: false,
		    userId:null,
		    userInfo:{
		    	 	userId:null,
		    		userName:null,
		    		accountID:null,
						avatar:null,
						name:null,
						token:null,
		    },
		    loadMessageList:true,
		    routerInfo:{
		    		currentPageName:null
		    },
		    messageList:{
		    		data:null,
		    		timestamp:null
		    },
		    sendMessage:{
		    	chatId:null,
		    	data:null,
		    	chatMsgType:null
		    }
	  },
	  mutations: {
		    changeUserLoginState (state,data) {
			      // 变更状态
			      state.isLogin=data.isLogin;
			      if(data.isLogin){
			      	 	state.userId=data.userId;
				      	state.userInfo={
					      		userId:data.userId,
						    		userName:data.userName,
						    		accountID:data.accountID,
										avatar:data.avatar,
										name:data.name,
										token:data.token
								};
			      }else{
			      		state.userId=null;
			      		state.userInfo-null;
			      };			      
		    },
		    loadMessageList(state,data){
			    	state.messageList.data=data.data;
			    	state.messageList.timestamp=new Date().getTime();
		    },
		    topMessageList(state,data){
			    	var messageList = state.messageList.data;
			    	var newMsgItem=data.newMsgItem;
			    	var topArray=[newMsgItem];
			    	messageList=topArray.concat(messageList);
			    	state.messageList.data=messageList;
			    	state.messageList.timestamp=new Date().getTime();
		    },
		    upDateMessageList(state,data){
			    	var messageList = state.messageList.data;
			    	var chatID = data.chatID;
			    	var newLastMsg=data.newLastMsg==undefined?null:data.newLastMsg;
			    	var lastReadTime=data.lastReadTime==undefined?null:data.lastReadTime;
			    	messageList.forEach(item=>{
							if(chatID == item.chat._id){
								newLastMsg!=null?item.lastChatMsg=newLastMsg:null;
								lastReadTime!=null?item.chatMemInfo.lastReadTime=lastReadTime:null;
							};
						});
						messageList.sort((a,b)=>{
							return (a.lastChatMsg==undefined?a.chat.createTime:a.lastChatMsg.sendTime)<(b.lastChatMsg==undefined?b.chat.createTime:b.lastChatMsg.sendTime)
						});
		    		state.messageList.timestamp=new Date().getTime();
		    },
		    changeCurrentPageName (state,data) {
		    		state.routerInfo.currentPageName = data.currentPageName;
		    },
		    sendMessage (state,data){
		    	if(data.chatId!=null){
			    	state.sendMessage =	{
				    	chatId:data.chatId,
				    	data:data.data,
				    	chatMsgType:data.chatMsgType
				    };
		    	}else{
		    		state.sendMessage=null
		    	};
		    }
		    
	  }, 
		actions: {
		    getUserLoginState (context) {
		     		context.commit('increment')
		    },
		    get_network_data_error_code (context) {
		    		 context.commit('increment')
		    }
	  }
});

export default store
